<?PHP

/*
 * Copyright (C) 2011-2012 Joachim Barthel
 * 
 * Version: 0.3
 * 
 * $Id: oxads.php 116 2012-09-30 12:23:03Z jobarthel@gmail.com $
 * 
 */

class WebAds {

    var $aLang;
    var $sWebsite;

	
    function openBanner($cStyle,$adMode)
    {
        include '../../config.inc.php';
        include 'config.inc.php';
        include $this->sShopDir.'/out/basic/'.$this->sLang.'/oxads_lang.php';

        if (substr($adMode,0,1) != 'i') {
        echo '<!DOCTYPE  HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';
        echo '<html>';
        echo '<head>';
        echo '<title>'.$aLang['OXADS_ADHINT'].'</title>';
        if (substr($adMode,0,1) == 'r')
            echo '<meta http-equiv="refresh" content="'.substr($adMode,1).'">';
        echo '<link rel="stylesheet" type="text/css" href="'.$this->sShopURL.'/modules/oxads/'.$cStyle.'.css">';
        /*echo '<script type="text/javascript">';
        echo 'function enableOxAds ()';
        echo '{';
        echo 'Timer = setTimeout(\'reloadOxAds()\' , 2000);';
        echo '}';
        echo 'function reloadOxAds ()';
        echo '{';
        echo 'alert(\'reloadOxAds\');';
        echo 'document.getElementById("adtable").innerHTML = "abc"';
        //echo 'Timer = setTimeout(\'reloadOxAds()\' , 3000);';
        echo '}';
        echo '</script>';*/
        echo '</head>';
        echo '<body class="oxad">';
        }
    }
	
	
    function closeBanner($adMode)
    {
        if (substr($adMode,0,1) != 'i') {
            echo '</body></html>';
        }
    }


    function openDB()
    {
        include '../../config.inc.php';
        include 'config.inc.php';

        $dbConn = 'mysql:host='.$this->dbHost.';port=3306;dbname='.$this->dbName;
        $dbUser = $this->dbUser;
        $dbPass = $this->dbPwd;

        $dbh = new PDO($dbConn, $dbUser, $dbPass); 
        //$dbh->exec('set names "utf8"');

        if (!empty($dbh)) 
            return $dbh;
        else
            return 0;
    }


    function closeDB($dbh)
    {
        $dbh = NULL;
    }


    function getActionArticles($dbh,$actionID)
    {
        include '../../config.inc.php';
        include 'config.inc.php';
        
        $sql = 'SHOW COLUMNS FROM oxactions WHERE field=\'OXTYPE\'';
        $stmt = $dbh->prepare($sql);
        $stmt->execute();
        if ($stmt->rowCount() != 0)
            $fieldOXTYPE = 'oxactions.oxtype,';
        else {
            $fieldOXTYPE = '';
        }

        $sql = 'SELECT '.$fieldOXTYPE.' oxarticles.oxid, oxarticles.oxparentid, oxarticles.oxtitle, '
             . 'oxarticles.oxshortdesc, oxarticles.oxprice, oxarticles.oxtprice, oxarticles.oxvarminprice, '
             . 'oxarticles.oxvarcount, oxarticles.oxicon, oxarticles.oxpic1 '
             . 'FROM oxactions,oxactions2article,oxarticles '
             . 'WHERE oxactions.oxid=oxactions2article.oxactionid '
             . 'AND oxarticles.oxid=oxactions2article.oxartid '
             . 'AND oxactions.OXID=\''.$actionID.'\' '
             . 'AND oxarticles.OXACTIVE=1 '
             . 'ORDER BY oxactions2article.oxsort ';
//echo $sql;
        $stmt = $dbh->prepare($sql);
        $stmt->execute();
        $dbData = $stmt->fetchAll(PDO::FETCH_ASSOC);
        if (count($dbData) == 0)
            echo $sql;
        else
            shuffle($dbData);
        
        return $dbData;
    }

    function formatAdvertisement($artList,$adBanner)
    {
        include '../../config.inc.php';
        include 'config.inc.php';
        include $this->sShopDir.'/out/basic/'.$this->sLang.'/oxads_lang.php';

        if (count($artList) == 0)
            return;
        
        switch ($adBanner) {
            case 'LargeBanner' :
                $tableStyle = 'horizontal';
                $tableHeight = 90;
                $tableWidth = 720;
                break;
            case 'MidBanner' :
                $tableStyle = 'horizontal';
                $tableHeight = 90;
                $tableWidth = 460;
                break;
            case 'WideColumn' :
                $tableStyle = 'vertical';
                $tableHeight = 630;
                $tableWidth = 190;
                $headHeight = 40;
                $rowHeight = 98;
                $maxArticles = 5;
                break;
            case 'SmallColumn' :
                $tableStyle = 'vertical';
                $tableHeight = 500;
                $tableWidth = 160;
                $headHeight = 40;
                $rowHeight = 98;
                $maxArticles = 4;
                break;
        }

        // Firefox has a problem with the 'adhint' class
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox'))
            echo '<div>'.$aLang['OXADS_ADHINT'].'</div>';
        else
            echo '<div class="adhint">'.$aLang['OXADS_ADHINT'].'</div>';
        echo '<div class="maintable" id="adtable" style="height:'.$tableHeight.'px; width:'.$tableWidth.'px;">';
        
        $reducedPrices = FALSE;

        if ($tableStyle == 'vertical')
            {
            echo '<div class="header" style="height:'.$headHeight.'px;">'.$this->sShopname.'</div >';
            $rowCount = 0;
            foreach($artList as $article) {
                $rowCount++;
            }
            for ($i=0; $i<$maxArticles; $i++) {
                $article = $artList[$i];
                echo '<div class="space"> </div>';
                echo '<div style="height:'.$rowHeight.'px;">';
                if (empty($article['oxicon']))
                    $article['oxicon'] = substr($article['oxpic1'],0,strlen($article['oxpic1'])-4).$this->sIconExt.substr($article['oxpic1'],-4);
                if ($this->bUsePiwikCampaigns)
                    $sCampaign = "&".$this->sPiwikCampaignVarName."=".$this->sWebsite."&".$this->sPiwikKeywordVarName."=".$article['oxtitle'];
                else
                    $sCampaign = "";
                echo '<div class="image" style="height:'.$rowHeight.'px;width:60px;">'
                   . '<a href="'.$this->sShopURL.'/index.php?cl=details&anid='.$article['oxid'].$sCampaign.'" target="_blank">'
                   . '<img src="'.$this->sShopURL.$this->sIconPath.$article['oxicon'].'">'
                   . '</a></div>';
                echo '<div class="description" style="height:'.$rowHeight.'px;width:'.($tableWidth-65).'px;">'
                   . '<div class="title">'
                   . '<a href="'.$this->sShopURL.'/index.php?cl=details&anid='.$article['oxid'].$sCampaign.'" target="_blank">'.$article['oxtitle'].'</a>'
                   . '</div>';
                if (!empty($article['oxshortdesc']))
                    echo '<div class="desc">'.$article['oxshortdesc'].'</div>';

                echo '<div class="price">';
                if ($article['oxvarcount'] == 0) {
                    if (($article['oxprice'] < $article['oxtprice']) && ($adBanner == 'WideColumn')) {
                        echo '<span class="tiltedstrike">&thinsp;<span class="oldprice">'.number_format($article['oxtprice'],2,',','').'</span>&thinsp;</span>&nbsp;';
                        $reducedPrices = TRUE;
                    }
                    echo '<span class="price">'.number_format($article['oxprice'],2,',','').'&nbsp;'.$this->sCurrency.'<sup>*</sup></span>';
                }
                else {
                    echo '<span class="price"><span style="font-size:0.8em;">ab</span> '.number_format($article['oxvarminprice'],2,',','').'&nbsp;'.$this->sCurrency.'<sup>*</sup></span>';
                }
                echo '</div>';
                //echo '<div class="gotobutton"><button onclick="window.parent.location=\''.$this->sShopURL.'/index.php?cl=details&anid='.$article['oxid'].'\'">'.$aLang['OXADS_GOTOSHOP'].'</button></div>';
                echo '<div class="gotobutton">';
                echo '<a class="oxadbutton" href="'.$this->sShopURL.'/index.php?cl=details&anid='.$article['oxid'].$sCampaign.'" target="_blank">'.$aLang['OXADS_GOTOSHOP'].'</a>';
                echo '</div>';
                echo '<div class="clear"></div>';
                echo '</div>';
                }
            echo '<div class="footer" style="top:'.($tableHeight-50).'px;width:'.$tableWidth.'px;">';
            echo '<div class="sepline" style="width:'.($tableWidth-10).'px;"></div>';
            echo '<div class="space"> </div>';
            
            echo '<div class="pricehint">';
            echo '<sup>*</sup><a href="'.$this->sShopURL.'/Versand-und-Kosten/" target="_blank">';
            echo $aLang['OXADS_PRICEHINT'];
            if ($reducedPrices)
                echo '<br />'.$aLang['OXADS_REDUCEDPRICES'];
            echo '</a></div>';
            
            echo '</div>';
            }
        else {
            echo '<tr>';
            foreach($artList as $article) {
                echo '<td class="image"><img src="'.$this->sShopURL.'/out/pictures/icon/'.$article['oxicon'].'"></td>';
                echo '<td><span class="title"><a href="'.$this->sShopURL.'/index.php?cl=details&anid='.$article['oxid'].'" target="_blank">'.$article['oxtitle'].'</a></span><br>';
                if (!empty($article['oxshortdesc']))
                        echo '<span class="desc">'.$article['oxshortdesc'].'</span><br>';
                echo '<span class="price">'.number_format($article['oxprice'],2,',','').'&nbsp;'.$this->sCurrency.'<sup>*</sup></span><br>';
                echo '<button onclick="window.parent.location=\''.$this->sShopURL.'/index.php?cl=details&anid='.$article['oxid'].'\'">Zum Shop</button></td>';
            }
            echo '</tr>';
            echo '<tr><td colspan="8"><span class="pricehint"><a href="'.$this->sShopURL.'/Versand-und-Kosten/" target="_blank"><sup>*</sup>Alle Preise inkl. MwSt., zzgl. Versandkosten.</a></span></td></tr>';
        }


        echo '</div>';
    }
    
    
    function showCachedAdvertisement($actionID, $bannerFormat)
    {
        include '../../config.inc.php';
        include 'config.inc.php';
        $cachePathFile = $this->sShopDir.'/modules/oxads/cache/'.$actionID.'.000';

        $fp = @fopen($cachePathFile,"r");
        if ($fp) {
            while (! feof ($fp)) {
                $html = fgets ($fp);
                echo $html;
            }
            fclose($fp);
        }
        else {
            echo 'Cache file not found.';
        }
    }
    
    
    function saveStats($adHost)
    {
        include '../../config.inc.php';
        include 'config.inc.php';

        if (empty($this->sLogging))
            return;
        
        if (!empty($adHost)) {
            $statsPathFile = $this->sShopDir.'/modules/oxads/stats/'.$adHost;
            //echo $statsPathFile;
            $fp = @fopen($statsPathFile,"r+");
            if ($fp) {

                switch ($this->sLogging) {
                    case 'each' :
                        fseek($fp, SEEK_END);
                        fputs($fp, date("Y-m-d G:i:s")."\n");
                        break;
                    case 'dmy' :
                        $cYear = '';
                        $cMonth = '';
                        $cDay = '';
                        while (!feof($fp)) {
                            $fpos = ftell($fp);    
                            $line = fgets($fp,4096);
                            $cNeedle = date("Y") . ',';
                            if ((strpos($line,$cNeedle) !== FALSE) && (empty($cYear))) {
                                $nCount = substr($line,6) + 1;
                                fseek($fp,$fpos);
                                fputs($fp, date("Y").', '.sprintf("%1$ 9d",$nCount)."\n");
                                $fpos = ftell($fp); 
                                $cYear = 'found';
                            }
                            $cNeedle = date("Y-m") . ',';
                            if ((strpos($line,$cNeedle) !== FALSE) && (empty($cMonth))) {
                                $nCount = substr($line,9) + 1;
                                fseek($fp,$fpos);
                                fputs($fp, date("Y-m").', '.sprintf("%1$ 9d",$nCount)."\n");
                                $fpos = ftell($fp); 
                                $cMonth = 'found';
                            }
                            $cNeedle = date("Y-m-d") . ',';
                            if ((strpos($line,$cNeedle) !== FALSE) && (empty($cDay))) {
                                $nCount = substr($line,12) + 1;
                                fseek($fp,$fpos);
                                fputs($fp, date("Y-m-d").', '.sprintf("%1$ 9d",$nCount)."\n");
                                $fpos = ftell($fp); 
                                $cDay = 'found';
                            }
                        }
                        if (empty($cYear))
                            fputs($fp, date("Y").', '.sprintf("%1$ 9d",1)."\n");
                        if (empty($cMonth))
                            fputs($fp, date("Y-m").', '.sprintf("%1$ 9d",1)."\n");
                        if (empty($cDay))
                            fputs($fp, date("Y-m-d").', '.sprintf("%1$ 9d",1)."\n");
                        break;
                }
                fclose($fp);
            }
            
        }
    }
	
}


$actionID = isset($_POST['id']) ? $_POST['id'] : $_GET['id'];
$styleSheet = isset($_POST['s']) ? $_POST['s'] : $_GET['s'];
$bannerFormat = isset($_POST['f']) ? $_POST['f'] : $_GET['f'];
$adMode = isset($_POST['m']) ? $_POST['m'] : $_GET['m'];
$adHost = isset($_POST['h']) ? $_POST['h'] : $_GET['h'];


//$actionID = '83f69aaf781165afece1b953177e6e95';
//$styleSheet = 'default';
//$bannerFormat = 'WideColumn';
//$adMode = 'r5';
//$adHost = 'localhost';
$ads = new WebAds;
$ads->saveStats($adHost);
$ads->sWebsite = $adHost;
if (substr($adMode, 0, 1) == 'c') {
    $ads->showCachedAdvertisement($actionID, $bannerFormat);
}
else {
    $ads->openBanner($styleSheet,$adMode);
    $dbh = $ads->openDB();
    $artList = $ads->getActionArticles($dbh, $actionID);
    $ads->formatAdvertisement($artList, $bannerFormat);
    $ads->closeDB($dbh);
    $ads->closeBanner($adMode);
}

?>